package cn.pugle.mianshi.thread1To10;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * <p> Created by tzp on 2017/9/6.
 */
@SuppressWarnings({"Duplicates", "AlibabaRemoveCommentedCode"})
public class PrintToTen3 implements Runnable {
    private volatile int count = 1;

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            while (count <= MAX) {
                if (count % 2 == 0 && count <= MAX) {//这里再判一次, 就不会打印101了
                    //"打印, 自增" 这个写法就没有1324问题了
                    System.out.println(Thread.currentThread() + " " + count);
                    count++;
                }
                Thread.yield();
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            while (count <= MAX) {
                if (count % 2 == 1 && count <= MAX) {
                    System.out.println(Thread.currentThread() + " " + count);
                    count++;
                }
                Thread.yield();
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen3().run();
    }
}
